// Vue 3 Auth Management Module
import { reactive, ref, watch } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';

// Reactive auth state
export const authState = reactive({
    currentUser: null,
    isCheckingAuth: false,
    lastCheckTime: 0,
    isAuthenticated: false
});

const AUTH_CHECK_INTERVAL = 5000; // Minimum time between auth checks

// Configure axios defaults
axios.defaults.baseURL = window.location.origin;
axios.defaults.withCredentials = true; // 重要：确保发送cookies

// Add response interceptor to handle 401 errors
axios.interceptors.response.use(response => {
    return response;
}, error => {
    if (error.response && error.response.status === 401) {
        // Clear user state
        authState.currentUser = null;
        authState.isAuthenticated = false;
        // Only redirect to login for protected pages
        if (isProtectedPage() && !window.location.pathname.includes('/login.html')) {
            window.location.href = '/login.html?redirect=' + encodeURIComponent(window.location.href);
        }
    }
    return Promise.reject(error);
});

// Utility functions
export function isAuthenticated() {
    return authState.isAuthenticated;
}

export function getCurrentUser() {
    return authState.currentUser;
}

// Check if current page requires authentication
function isProtectedPage() {
    const protectedPages = ['/profile.html', '/upload.html'];
    const currentPath = window.location.pathname.toLowerCase();
    return protectedPages.some(page => currentPath.endsWith(page.toLowerCase()));
}

// Check if current page is login or register page
function isAuthPage() {
    const authPages = ['/login.html', '/register.html'];
    const currentPath = window.location.pathname.toLowerCase();
    return authPages.some(page => currentPath.endsWith(page.toLowerCase()));
}

// Show toast message (Vue 3 compatible)
export function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');

    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
        </div>
    `;

    let toastContainer = document.getElementById('toastContainer');
    if (!toastContainer) {
        // Create toast container if it doesn't exist
        toastContainer = document.createElement('div');
        toastContainer.id = 'toastContainer';
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '1080';
        document.body.appendChild(toastContainer);
    }

    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();

    // Remove toast after it's hidden
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

// Check authentication status
export async function checkAuthStatus(forceCheck = false) {
    console.log('checkAuthStatus called, forceCheck:', forceCheck);
    
    // Skip auth check on login/register pages unless forced
    if (isAuthPage() && !forceCheck) {
        console.log('Skipping auth check on auth page');
        return false;
    }
    
    // 避免重复检查 - 等待当前检查完成
    if (authState.isCheckingAuth) {
        console.log('Auth check already in progress, waiting...');
        // 等待当前检查完成，然后返回结果
        return new Promise((resolve) => {
            const checkInterval = setInterval(() => {
                if (!authState.isCheckingAuth) {
                    clearInterval(checkInterval);
                    resolve(authState.isAuthenticated);
                }
            }, 50);
        });
    }
    
    // 如果不是强制检查，且距离上次检查时间不够长，则跳过
    const now = Date.now();
    if (!forceCheck && (now - authState.lastCheckTime < AUTH_CHECK_INTERVAL)) {
        console.log('Using cached auth result:', authState.isAuthenticated);
        return authState.isAuthenticated;
    }

    authState.isCheckingAuth = true;
    try {
        console.log('Making API call to /api/auth/user...');
        const response = await axios.get('/api/auth/user');
        console.log('API response status:', response.status);
        console.log('API response data:', response.data);
        
        if (response.data && response.status === 200) {
            authState.currentUser = response.data;
            authState.isAuthenticated = true;
            authState.lastCheckTime = now;
            updateAuthUI(true, response.data);
            console.log('Authentication successful, user:', response.data.username);
            return true;
        } else {
            console.log('API response invalid or empty');
            authState.currentUser = null;
            authState.isAuthenticated = false;
            updateAuthUI(false);
            return false;
        }
    } catch (error) {
        console.error('Auth check API call failed:', error);
        if (error.response && error.response.status === 401) {
            console.log('401 error, user not authenticated');
            authState.currentUser = null;
            authState.isAuthenticated = false;
            updateAuthUI(false);
        }
        return false;
    } finally {
        authState.isCheckingAuth = false;
        console.log('Auth check completed');
    }
}

// Update UI based on authentication status
function updateAuthUI(isAuthenticated, userData = null) {
    if (!document.body) return; // 如果DOM还没有加载，直接返回

    const elements = {
        loginBtn: document.getElementById('loginBtn'),
        registerBtn: document.getElementById('registerBtn'),
        profileBtn: document.getElementById('profileBtn'),
        uploadBtn: document.getElementById('uploadBtn'),
        logoutBtn: document.getElementById('logoutBtn'),
        usernameDisplay: document.getElementById('usernameDisplay'),
        authButtons: document.getElementById('authButtons')
    };

    if (isAuthenticated && userData) {
        // 已登录状态
        authState.currentUser = userData;
        authState.isAuthenticated = true;
        
        for (const [key, element] of Object.entries(elements)) {
            if (!element) continue;
            
            switch (key) {
                case 'loginBtn':
                case 'registerBtn':
                    element.style.display = 'none';
                    break;
                case 'profileBtn':
                case 'uploadBtn':
                case 'logoutBtn':
                    element.style.display = 'block';
                    break;
                case 'usernameDisplay':
                    element.textContent = userData.username;
                    element.style.display = 'inline';
                    break;
                case 'authButtons':
                    element.style.display = 'none';
                    break;
            }
        }
    } else {
        // 未登录状态
        authState.currentUser = null;
        authState.isAuthenticated = false;
        
        for (const [key, element] of Object.entries(elements)) {
            if (!element) continue;
            
            switch (key) {
                case 'loginBtn':
                case 'registerBtn':
                    element.style.display = 'block';
                    break;
                case 'profileBtn':
                case 'uploadBtn':
                case 'logoutBtn':
                    element.style.display = 'none';
                    break;
                case 'usernameDisplay':
                    element.textContent = '';
                    element.style.display = 'none';
                    break;
                case 'authButtons':
                    element.style.display = 'block';
                    break;
            }
        }
    }
}

// Login function
export async function login(username, password) {
    try {
        console.log('Attempting login for user:', username);
        const response = await axios.post('/api/auth/login', {
            username: username,
            password: password
        });

        if (response.data && response.data.user) {
            console.log('Login successful:', response.data);
            
            // 立即检查认证状态
            const authSuccess = await checkAuthStatus(true);
            if (!authSuccess) {
                throw new Error('Authentication failed after login');
            }
            
            // 获取重定向URL
            const params = new URLSearchParams(window.location.search);
            const redirectUrl = params.get('redirect') || '/';
            
            // 等待一小段时间确保session和UI都已更新
            setTimeout(() => {
                window.location.href = decodeURIComponent(redirectUrl);
            }, 100);
            
            return true;
        }
    } catch (error) {
        console.error('Login failed:', error);
        throw error;
    }
    return false;
}

// Logout function
export async function logout() {
    try {
        console.log('Attempting logout...');
        // Call logout API to clear server-side session
        await axios.post('/api/auth/logout');
        console.log('Logout API call successful');
    } catch (error) {
        console.error('Logout API call failed:', error);
    }
    
    // Clear client-side data
    authState.currentUser = null;
    authState.isAuthenticated = false;
    updateAuthUI(false);
    window.location.href = '/login.html';
}

// Initialize auth check on page load
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded, current page:', window.location.pathname);
    
    // Only check auth for pages that need it, and avoid auth pages
    if (!isAuthPage()) {
        console.log('Checking auth status on non-auth page');
        checkAuthStatus(false);
    } else {
        console.log('Skipping auth check on auth page');
        // Clear any existing auth state on auth pages
        authState.currentUser = null;
        authState.isAuthenticated = false;
        updateAuthUI(false);
    }
});

// 定期检查认证状态 - 但不在登录/注册页面
setInterval(() => {
    if (!isAuthPage()) {
        checkAuthStatus();
    }
}, AUTH_CHECK_INTERVAL);

// Legacy support - 为了兼容现有代码，保留这些全局变量和函数
window.currentUser = authState.currentUser;
window.checkAuthStatus = checkAuthStatus;
window.login = login;
window.logout = logout;
window.showToast = showToast;

// Watch for currentUser changes and update global variable
watch(() => authState.currentUser, (newUser) => {
    window.currentUser = newUser;
});
